package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.ClientTrace;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IClientService;
import cn.wolfcode.crm.service.IClientTraceService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("clientTrace")
public class ClientTraceController {

    @Autowired
    private IClientTraceService clientTraceService;
    @Autowired
    private IClientService clientService;

    @RequestMapping("view")
    public String view() {
        return "clientTrace/list";
    }

    @RequestMapping("list")
    @ResponseBody
    public PageResult list(QueryObject qo) {
        PageResult result = clientTraceService.query(qo);
        return result;
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(ClientTrace clientTrace) {
        JsonResult result = new JsonResult();
        try {
            if (clientTrace.getId() != null) {
                clientTraceService.updateByPrimaryKey(clientTrace);
            } else {
                clientTraceService.insert(clientTrace);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.mark("操作失败");
        }
        return result;
    }

    @RequestMapping("audit")
    @ResponseBody
    /**
     *审核操作
     */
    public JsonResult audit(ClientTrace clientTrace) {
        JsonResult result = new JsonResult();
        try {
            clientTraceService.audit(clientTrace);
        } catch (Exception e) {
            e.printStackTrace();
            return result.mark("操作失败");
        }
        return result;
    }

    //跟踪操作
    @RequestMapping("traced")
    @ResponseBody
    public JsonResult traced(ClientTrace clientTrace) {
        JsonResult result = new JsonResult();
        try {
            clientService.traced(clientTrace.getClient().getId());
            clientService.updateSaleMan(clientTrace);
            if (clientTrace.getClient().getTraceNum() > 0) {
                //跟踪同时把跟踪表的最新跟踪时间更新
                clientTrace.setLastTraceTime(new Date());
                clientTraceService.updateByClientId(clientTrace);
            } else {
                clientTraceService.insert(clientTrace);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.mark("操作失败");
        }
        return result;
    }
}
